﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class Hate : MonoBehaviour {
	public Vector3 origin_pos;
	public float track_distance;
	[SerializeField]
	public bool have_hate;

	private Dictionary<GameObject , int> hate_you = new Dictionary<GameObject, int>();
	public int hate_num;

	// Use this for initialization
	void Start ()
	{
		hate_num = 10;
		have_hate = false;
		Refresh_origin_pos();
	}


	public void Refresh_origin_pos()
	{
		origin_pos = transform.position;
	}

	public void Refresh_hate_list()
	{
		if (hate_you.Count > 0) 
		{
			hate_you = (from entry in hate_you 
						orderby entry.Value ascending
						select entry).ToDictionary(pair => pair.Key, pair => pair.Value);
		}
	}

	public void add_hate(GameObject obj , int hate)
	{
		if (hate_you.Count < hate_num)
		{
			if (hate_you.ContainsKey(obj)) 
			{
				hate_you[obj] += hate;
			}
			else
			{
				hate_you.Add(obj , hate);
			}
		}
		else if (hate >  hate_you.Values.Min()) 
		{
			hate_you.Remove(hate_you.ElementAt(hate_num -1).Key);
			hate_you.Add(obj , hate);
		}
		Refresh_hate_list();
		have_hate = true;
	}
	
	public void Clear_hate()
	{
		foreach (KeyValuePair<GameObject,int> obj in hate_you) 
		{
			hate_you.Remove(obj.Key);
		}
		have_hate = false;
	}


	public bool remove_hate(GameObject obj)
	{	
		bool flag = hate_you.Remove(obj);
		if (hate_you.Count <= 0) 
		{
			have_hate = false;
		}
		return flag;
	}

	public int get_hate(GameObject obj)
	{
		return hate_you[obj];
	}

	public GameObject get_hate(int num)
	{
		if (!have_hate) 
		{
			return null;
		}
		return hate_you.ElementAt(num-1).Key;
	}


	
	// Update is called once per frame
	void Update ()
	{
		Character p_cot = gameObject.GetComponent<Character>();

		Vector3 pos = origin_pos;
		if (!p_cot.monster && !p_cot.leader) 
		{
			pos = p_cot.follw_target.transform.position;
		}
		GameObject obj = get_hate(1);
		if (obj && Vector3.Distance(obj.transform.position, pos) > track_distance) 
		{
			remove_hate(obj);
			Refresh_hate_list();
		}
	}
}
